<?php
// +----------------------------------------------------------------------
// | 海豚PHP框架 [ DolphinPHP ]
// +----------------------------------------------------------------------
// | 版权所有 2016~2017 河源市卓锐科技有限公司 [ http://www.zrthink.com ]
// +----------------------------------------------------------------------
// | 官方网站: http://dolphinphp.com
// +----------------------------------------------------------------------
// | 开源协议 ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------

// 门户模块公共函数库
use think\Db;

if (!function_exists('get_column_name')) {
    /**
     * 获取栏目名称
     * @param int $cid 栏目id
     * @author 蔡伟明 <314013107@qq.com>
     * @return string
     */
    function get_column_name($cid = 0)
    {
        $column_list = model('cat/column')->getList();
        return isset($column_list[$cid]) ? $column_list[$cid]['name'] : '';
    }
}


if (!function_exists('table_exist')) {
    /**
     * 检查附加表是否存在
     * @param string $table_name 附加表名
     * @author 蔡伟明 <314013107@qq.com>
     * @return string
     */
    function table_exist($table_name = '')
    {
        return true == Db::query("SHOW TABLES LIKE '{$table_name}'");
    }
}

if (!function_exists('time_tran')) {
    /**
     * 转换时间
     * @param int $timer 时间戳
     * @author 蔡伟明 <314013107@qq.com>
     * @return string
     */
    function time_tran($timer)
    {
        $diff = $_SERVER['REQUEST_TIME'] - $timer;
        $day = floor($diff / 86400);
        $free = $diff % 86400;
        if ($day > 0) {
            return $day . " 天前";
        } else {
            if ($free > 0) {
                $hour = floor($free / 3600);
                $free = $free % 3600;
                if ($hour > 0) {
                    return $hour . " 小时前";
                } else {
                    if ($free > 0) {
                        $min = floor($free / 60);
                        $free = $free % 60;
                        if ($min > 0) {
                            return $min . " 分钟前";
                        } else {
                            if ($free > 0) {
                                return $free . " 秒前";
                            } else {
                                return '刚刚';
                            }
                        }
                    } else {
                        return '刚刚';
                    }
                }
            } else {
                return '刚刚';
            }
        }
    }
}

/**
 * @param $data
 * @return \think\response\Json
 * 接口请求成功
 */
function returnOk($data)
{
    $data = [
        'code' => 200,
        'data' => $data,
        'message' => "请求成功"
    ];
    return json($data);
}

/**
 * @param $message
 * @return \think\response\Json
 * 接口请求失败
 */
function returnError($message)
{
    $data = [
        'code' => 500,
        'message' => $message
    ];
    return json($data);
}

/**
 * @param $str
 * @return mixed
 * 去除空格
 */
function trimall($str)//删除空格
{
    $oldchar=array(" ","　","\t","\n","\r");
    $newchar=array("","","","","");
    return str_replace($oldchar,$newchar,$str);
}

/**
 * @param $phone
 * @return int
 * 手机号验证
 */
function verPhone($phone)
{
    if (preg_match("/^134[0-8]\d{7}$|^13[^4]\d{8}$|^14[5-9]\d{8}$|^15[^4]\d{8}$|^16[6]\d{8}$|^17[0-8]\d{8}$|^18[\d]{9}$|^19[8,9]\d{8}$/", $phone)) {
        return 1;
    } else {
        return 0;
    }
}

/**
 * @param $phone
 * @return int
 * 手机号验证(只验证位数与数据类型)
 */
function verPhone2($phone)
{
    if (preg_match("/^[1]\d{10}$/", $phone)) {
        return 1;
    } else {
        return 0;
    }
}

/**
 * @param $password
 * @return int
 * 密码验证 6-18位字母数字混合
 */
 function verpassword($password){
    if (preg_match("/^[a-zA-Z0-9]{6,18}$/",$password)){
        return 1;
     }else{
        return 0;
    }
 }

/**
 * @param $name
 * @return int
 * 真实姓名验证
 */
function verName($name)
{
    if (preg_match("/^([\xe4-\xe9][\x80-\xbf]{2}){2,4}$/", $name)) {
        return 1;
    } else {
        return 0;
    }
}

/**
 * @param $s
 * @return bool
 * 银行卡号验证
 */
function luhm($no) {
    $arr_no = str_split($no);
    $last_n = $arr_no[count($arr_no)-1];
    krsort($arr_no);
    $i = 1;
    $total = 0;
    foreach ($arr_no as $n){
        if($i%2==0){
            $ix = $n*2;
            if($ix>=10){
                $nx = 1 + ($ix % 10);
                $total += $nx;
            }else{
                $total += $ix;
            }
        }else{
            $total += $n;
        }
        $i++;
    }
    $total -= $last_n;
    $total *= 9;
    if($last_n == ($total%10)){
        return true;
    }else{
        return false;
    }
}


/**
 * @param $url
 * @return mixed
 * 发起https请求GET
 */
function curl_get_https($url)
{
    $curl = curl_init(); // 启动一个CURL会话
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_HEADER, 0);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true); // 跳过证书检查
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);  // 从证书中检查SSL加密算法是否存在
    $tmpInfo = curl_exec($curl);     //返回api的json对象
    //关闭URL请求
    curl_close($curl);
    return $tmpInfo;    //返回json对象
}

/**
 * @param $url
 * @return mixed
 * 发起https请求POST
 */
function curl_post_https($url,$post_data)
{
    $curl = curl_init(); // 启动一个CURL会话
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_HEADER, 0);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    //设置post方式提交
    curl_setopt($curl, CURLOPT_POST, 1);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true); // 跳过证书检查
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);  // 从证书中检查SSL加密算法是否存在
    $tmpInfo = curl_exec($curl);     //返回api的json对象
    //关闭URL请求
    curl_close($curl);
    return $tmpInfo;    //返回json对象
}

/**
 * @param $base64_image_content
 * 图片上传
 */
function Image64($base64_image_content)
{
    if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result)) {
        $type = $result[2];
        $new_file = "uploads/qrcode/" . date('Ymd', time()) . "/";
        if (!file_exists($new_file)) {
//检查是否有该文件夹，如果没有就创建，并给予最高权限
            mkdir($new_file, 0700, true);
        }
        $new_file = $new_file . time() . ".{$type}";
        if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $base64_image_content)))) {
            return $new_file;
        } else {
            return 0;
        }
    }
}

//多文件处理
function upImage($picture)
{

    foreach($picture['name'] as $key=>$value) {
        $data['name'] = $picture['name'][$key];
        $data['type'] = $picture['type'][$key];
        $data['tmp_name'] = $picture['tmp_name'][$key];
        $data['error'] = $picture['error'][$key];
        $data['size'] = $picture['size'][$key];
        $info[]=verImage($data);

    }
    return $info;
}

function verImage($data){
    $new_file = "uploads/img/" . date('Ymd', time()) . "/";
    $rand=time().rand(10000,99999).".jpg";
    if ((($data["type"] == "image/gif")|| ($data["type"] == "image/jpeg")|| ($data["type"] == "image/pjpeg")|| ($data["type"] == "image/jpg")||($data["type"] == "image/png"))&& ($data["size"] < 6291456))//6MB
    {
        if ($data["error"] > 0)
        {
            $return=[
                'code'=>0,
                'message'=>"Return Code: " . $data["error"] . "<br />"
            ];
        }
        else
        {
            if (!file_exists($new_file)) {
//检查是否有该文件夹，如果没有就创建，并给予最高权限
                mkdir($new_file, 0700, true);
            }
                move_uploaded_file($data["tmp_name"],
                    $new_file .$rand);
            $return=[
                'code'=>200,
                'message'=>$new_file .$rand
            ];
        }
    }
    else
    {
        $return=[
            'code'=>0,
            'message'=>"文件格式有误"
        ];
    }
    return  $return;
}

//验证身份证是否有效
function validateIDCard($IDCard) {
    if (strlen($IDCard) == 18) {
        return check18IDCard($IDCard);
    } elseif ((strlen($IDCard) == 15)) {
        $IDCard = convertIDCard15to18($IDCard);
        return check18IDCard($IDCard);
    } else {
        return false;
    }
}

//计算身份证的最后一位验证码,根据国家标准GB 11643-1999
function calcIDCardCode($IDCardBody) {
    if (strlen($IDCardBody) != 17) {
        return false;
    }

    //加权因子
    $factor = array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);
    //校验码对应值
    $code = array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2');
    $checksum = 0;

    for ($i = 0; $i < strlen($IDCardBody); $i++) {
        $checksum += substr($IDCardBody, $i, 1) * $factor[$i];
    }

    return $code[$checksum % 11];
}

// 将15位身份证升级到18位
function convertIDCard15to18($IDCard) {
    if (strlen($IDCard) != 15) {
        return false;
    } else {
        // 如果身份证顺序码是996 997 998 999，这些是为百岁以上老人的特殊编码
        if (array_search(substr($IDCard, 12, 3), array('996', '997', '998', '999')) !== false) {
            $IDCard = substr($IDCard, 0, 6) . '18' . substr($IDCard, 6, 9);
        } else {
            $IDCard = substr($IDCard, 0, 6) . '19' . substr($IDCard, 6, 9);
        }
    }
    $IDCard = $IDCard . calcIDCardCode($IDCard);
    return $IDCard;
}

// 18位身份证校验码有效性检查
function check18IDCard($IDCard) {
    if (strlen($IDCard) != 18) {
        return false;
    }

    $IDCardBody = substr($IDCard, 0, 17); //身份证主体
    $IDCardCode = strtoupper(substr($IDCard, 17, 1)); //身份证最后一位的验证码

    if (calcIDCardCode($IDCardBody) != $IDCardCode) {
        return false;
    } else {
        return true;
    }
}

//和信通 短信接口
function send($phone,$content){
    $post['userid']=9682;
    $post['account']='wuyongyu';
    $post['password']='wu870708';
    $post['mobile']=$phone;
    $post['content']=$content;
    $post['sendTime']='';
    $post['action']='send';
    $post['extno']='';
    $return=curl_post_https('http://123.57.51.191:8888/sms.aspx',$post);

    return $return;
}

//XML转数组
function xmlToArray($xml){

    //禁止引用外部xml实体

    libxml_disable_entity_loader(true);

    $xmlstring = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);

    $val = json_decode(json_encode($xmlstring),true);

    return $val;

}